package com.zx.练习题.demo;

import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class T3 {

    private static final ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException {
        SynchronousQueue<String> queue = new SynchronousQueue<String>();

        AtomicInteger fail = new AtomicInteger(0);
        pool.execute(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    log.info("consumer1 start");
                    log.info("consumer1：get={}", queue.take());
                    Thread.sleep(500L);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        pool.execute(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    Thread.sleep(1000L);
                    log.info("1 start");
                    boolean offer = queue.offer("1_" + i);
                    if (!offer) {
                        fail.incrementAndGet();
                    }
                    log.info("1 end, offer={}", offer);
                    Thread.sleep(1000L);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        pool.execute(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    Thread.sleep(1000L);
                    log.info("2 start");
                    boolean offer = queue.offer("2_" + i);
                    if (!offer) {
                        fail.incrementAndGet();
                    }
                    log.info("2 end, offer={}", offer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        while (pool.getActiveCount() == 0 && queue.isEmpty()) {
            Thread.sleep(1000L);
        }
        pool.shutdown();
        log.info("fail={}", fail.get());
    }


}
